package main

import (
	"bufio"
	"fmt"
)

type WordsCounter int

func (wc *WordsCounter) Write(p []byte) (int, error) {
	// fmt.Println("words counter")
	// *wc = WordsCounter(len(p))
	// return 5, nil

	for i := 0; i < len(p); {
		n, _, err := bufio.ScanWords(p[i:], true)
		if err != nil {
			return 0, err
		}
		i += n
		(*wc)++
	}

	return int(*wc), nil
}

type LinesCounter int

func (lc *LinesCounter) Write(p []byte) (int, error) {
	for i := 0; i < len(p); {
		n, _, err := bufio.ScanLines(p, true)
		if err != nil {
			return 0, err
		}
		i += n
		(*lc)++
	}
	return int(*lc), nil
}

func main() {
	var wc WordsCounter
	// 两种调用方式 [1]
	wc.Write([]byte("hello world a b c"))
	fmt.Println(wc)

	wc = 0
	// [2]
	fmt.Fprintf(&wc, "hello, words counter")
	fmt.Println(wc)

	// ---------------
	var lc LinesCounter
	fmt.Fprintf(&lc, "line \n new line \n line 3\n sd\n a")
	fmt.Println(lc)

	lc = 0
	fmt.Fprintf(&lc, "%s\n%s\n", "hello", "world")
	fmt.Println(lc)
}
